package com.hbnu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbnu.mapper.RoomMapper;
import com.hbnu.mapper.RoomMemberMapper;
import com.hbnu.pojo.Room;
import com.hbnu.pojo.RoomMember;
import com.hbnu.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Random;


@Service
public class RoomServiceImpl implements RoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RoomMemberMapper roomMemberMapper;
    //创建房间
    @Override
    public Room createRoom(String roomName, String creatorId) {
        Room room = new Room();
        // 生成6位随机房间号
        Integer roomId = generateUniqueRoomId();
        room.setRoomId(roomId);
        room.setRoomName(roomName); //房间名
        room.setCreatorId(creatorId); //  设置创建者ID
        room.setStatus("waiting");  //设置房间状态为等待中
        room.setMaxPlayers(6);  //最大人数为6人
        room.setCurrentPlayers(1); //当前人数为1人
        room.setCreatedTime(LocalDateTime.now().toString());
        roomMapper.insert(room);

        //插入创建者为第一个房间成员
        RoomMember member = new RoomMember();
        member.setRoomId(room.getRoomId());
        member.setUserId(creatorId);
        member.setReadyStatus("notReady");
        member.setJoinTime(LocalDateTime.now().toString());
        roomMemberMapper.insert(member);

        return room;
    }

    //加入房间
    @Override
    public boolean joinRoom(Integer roomId, String userId) {
        Room room = roomMapper.selectById(roomId);
        //判断房间是否已满
        if (room.getCurrentPlayers() >= room.getMaxPlayers()) {
            return false;
        }
            //添加成员纪录
            RoomMember member = new RoomMember();
            member.setRoomId(roomId);
            member.setUserId(userId);
            member.setReadyStatus("notReady");
            member.setJoinTime(LocalDateTime.now().toString());
            roomMemberMapper.insert(member);

            //更新房间当前人数
            room.setCurrentPlayers(room.getCurrentPlayers() + 1);
            roomMapper.updateById(room);
            return true;
    }

    //状态切换为准备
    @Override
    public boolean setReady(Integer roomId, String userId) {
        QueryWrapper<RoomMember> wrapper = new QueryWrapper<>();
        wrapper.eq("room_id", roomId).eq("user_id", userId);
        RoomMember member = roomMemberMapper.selectOne(wrapper);
        if (member == null) return false;

        member.setReadyStatus("ready");
        roomMemberMapper.update(member, wrapper);
        return true;
    }
    //判断是否开始游戏
    @Override
    public boolean canStartGame(Integer roomId) {
        List<RoomMember> members = roomMemberMapper.selectList(
                new QueryWrapper<RoomMember>().eq("room_id", roomId)
        );
        return members.size() >= 2 &&
                members.stream().allMatch(m -> "ready".equals(m.getReadyStatus()));
    }

    //离开房间
    @Override
    public boolean leaveRoom(Integer roomId, String userId) {
        //1.删除RoomMember记录
        LambdaQueryWrapper<RoomMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoomMember::getRoomId, roomId).eq(RoomMember::getUserId, userId);
        roomMemberMapper.delete(wrapper);

        //2.检查该房间是否还有其他成员
        LambdaQueryWrapper<RoomMember> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(RoomMember::getRoomId, roomId);
        Long count = roomMemberMapper.selectCount(countWrapper);
        if (count == 0) {
            //3.如果该房间没有其他成员，则删除该房间
            roomMapper.deleteById(roomId);
        }
        return true;
    }

    /**
     * 生成唯一的6位房间号
     */
    private Integer generateUniqueRoomId() {
        Random random = new Random();
        Integer roomId;
        int attempts = 0;
        int maxAttempts = 100; // 最大尝试次数，避免无限循环
        
        do {
            // 生成100000-999999之间的6位数
            roomId = 100000 + random.nextInt(900000);
            attempts++;
            
            // 如果尝试次数过多，抛出异常
            if (attempts >= maxAttempts) {
                throw new RuntimeException("无法生成唯一的房间号，请稍后重试");
            }
        } while (roomMapper.selectById(roomId) != null); // 检查房间号是否已存在
        
        return roomId;
    }

    @Override
    public Room getRoomById(Integer roomId) {
        return roomMapper.selectById(roomId);
    }
    
    @Override
    public boolean addMemberToRoom(Integer roomId, String userId) {
        try {
            // 检查用户是否已在房间中
            QueryWrapper<RoomMember> wrapper = new QueryWrapper<>();
            wrapper.eq("room_id", roomId).eq("user_id", userId);
            RoomMember existingMember = roomMemberMapper.selectOne(wrapper);
            if (existingMember != null) {
                return true; // 用户已在房间中，返回成功
            }
            
            // 添加成员记录
            RoomMember member = new RoomMember();
            member.setRoomId(roomId);
            member.setUserId(userId);
            member.setReadyStatus("notReady");
            member.setJoinTime(LocalDateTime.now().toString());
            int insertResult = roomMemberMapper.insert(member);
            
            // 只有在成功插入成员记录后才更新房间人数
            if (insertResult > 0) {
                Room room = roomMapper.selectById(roomId);
                if (room != null) {
                    // 重新计算当前人数，确保数据一致性
                    QueryWrapper<RoomMember> countWrapper = new QueryWrapper<>();
                    countWrapper.eq("room_id", roomId);
                    Long memberCount = roomMemberMapper.selectCount(countWrapper);
                    room.setCurrentPlayers(memberCount.intValue());
                    roomMapper.updateById(room);
                }
            }
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean deleteRoom(Integer roomId) {
        try {
            // 删除房间成员记录
            LambdaQueryWrapper<RoomMember> memberWrapper = new LambdaQueryWrapper<>();
            memberWrapper.eq(RoomMember::getRoomId, roomId);
            roomMemberMapper.delete(memberWrapper);
            
            // 删除房间记录
            roomMapper.deleteById(roomId);
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public boolean isUserInRoom(Integer roomId, String userId) {
        try {
            QueryWrapper<RoomMember> wrapper = new QueryWrapper<>();
            wrapper.eq("room_id", roomId).eq("user_id", userId);
            RoomMember member = roomMemberMapper.selectOne(wrapper);
            return member != null;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<String> getOrderedRoomMembers(Integer roomId) {
        QueryWrapper<RoomMember> wrapper = new QueryWrapper<>();
        wrapper.eq("room_id", roomId).orderByAsc("join_time");
        List<RoomMember> members = roomMemberMapper.selectList(wrapper);
        return members.stream().map(RoomMember::getUserId).collect(Collectors.toList());
    }

}
